﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Century.Model;
using GKFX.Common.Business.BOL.Common;
using GKFX.Business.Repository;
using Century.Web.Security.Attributes
using GKFX.Common.UI.MVC;
using GKFX.Models.ViewModels;
using Century.EnterpriseLibrary.Configuration;
using System;
using GKFX.Common.Enumerations;
using System.Web;

namespace Century.Web.MVC.AdminArea
{
    [Authorization(Group = "", Name = "SiteManager")]
    public class PageManagementController : CenturyAdminBaseController
    {

        private string defaultImagePath = string.Format("{0}/{1}", ConfManager.Instance.FileExplorer.DefaultPath.ConfigValue, "page_header_default.jpg");

        #region [ Page detail ]

        /// <summary>
        /// Gets Page Detail
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Get(int? id)
        {
            SitePage page = null;
            if (id.HasValue)
            {
                page = PersistData.AvailablePages.FirstOrDefault(p => p.Id == id.Value);
                if (page != null)
                {
                    //set current page
                    Session["CurrentPageId"] = page.Id;
                }
                else
                {
                    return new RedirectResult("/Admin");
                }
            }

            return View(page);
        }

        #region Setting Tab

        /// <summary>
        /// Gets Page Settings Tab Content
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Settings(int? id)
        {
            ViewData["Layouts"] = PersistData.AllLayouts.ToList();
            if (id.HasValue)
            {
                SitePage page = PersistData.AvailablePages.First(p => p.Id == id.Value);
                return View(page);
            }
            else
            {
                return View(new SitePage());
            }
        }

        /// <summary>
        /// Saves Page Settings Tab Content
        /// </summary>
        /// <param name="sitePage"></param>
        /// <returns></returns>
        [HttpPost]
        public void Settings(SitePage sitePage)
        {
            SitePage page = PersistData.AvailablePages.First(p => p.Id == sitePage.Id);

            page.Name = sitePage.Name;
            page.LocalName = sitePage.LocalName;
            page.Title = sitePage.Title;
            page.Url = sitePage.Url;
            page.NodeOrder = sitePage.NodeOrder;
            page.MenuDescription = sitePage.MenuDescription;
            page.ImagePath = string.IsNullOrEmpty(sitePage.ImagePath.Trim()) ? defaultImagePath : sitePage.ImagePath;
            page.MenuImagePath = sitePage.MenuImagePath;

            // change home page
            if (!page.IsHomePage && sitePage.IsHomePage)
            {
                // remove homepage flag from old page
                SitePage oldHomePage = PersistData.AvailablePages.First(p => p.CountrySiteId == page.CountrySiteId && p.IsHomePage == true);
                oldHomePage.IsHomePage = false;
                PersistData.AvailablePages.Update(p => p.Id == oldHomePage.Id, oldHomePage);
                // set new page as homepage
                page.IsHomePage = true;
            }

            page.ShowInMenu = sitePage.ShowInMenu;
            page.IsPublished = sitePage.IsPublished;
            page.ShowInRightMenu = sitePage.ShowInRightMenu;

            PersistData.AvailablePages.Update(p => p.Id == page.Id, page);
            
            // if page layout is updated
            if (page.PageLayoutId != sitePage.PageLayoutId)
            {
                PersistDataUpdater.ChangePageLayout(page.Id, sitePage.PageLayoutId);
            }
        }

        #endregion

        #region Properties Tab

        /// <summary>
        /// Gets Page Settings Tab Content
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Properties(int? id)
        {
            if (id.HasValue)
            {
                SitePage page = PersistData.AvailablePages.First(p => p.Id == id.Value);
                return View(page);
            }
            else
            {
                return View(new SitePage());
            }
        }

        /// <summary>
        /// Saves Page Settings Tab Content
        /// </summary>
        /// <param name="sitePage"></param>
        /// <returns></returns>
        [HttpPost]
        public void Properties(SitePage sitePage)
        {
            SitePage page = PersistData.AvailablePages.First(p => p.Id == sitePage.Id);
            page.Description = sitePage.Description;
            page.Keywords = sitePage.Keywords;
            PersistData.AvailablePages.Update(p => p.Id == page.Id, page);
        }

        #endregion

        #region Advanced

        public ActionResult Advanced(int? id)
        {
            if (id.HasValue)
            {
                SitePage page = PersistData.AvailablePages.First(p => p.Id == id.Value);
                return View(page);
            }
            else
            {
                return View(new SitePage());
            }
        }

        public ActionResult AdvancedDetail(SitePageParameterType type)
        {
            return View(type);
        }

        [HttpPost]
        public void AdvancedCSS(FormCollection elements)
        {
            int SitePageId = Convert.ToInt32(elements["SitePageId"]);
            string Path = elements["CssPath"];

            SitePage page = PersistData.AvailablePages.First(p => p.Id == SitePageId);
            if (page != null && Path.Trim().Length > 0)
            {
                if (page.SitePageParameters != null && !page.SitePageParameters.Any(p => p.ParamValue == Path && p.ParamType == (int)SitePageParameterType.Css))
                {
                    PersistDataUpdater.AddParameterToPage(page, new SitePageParameter
                    {
                        ParamName = "CSS",
                        ParamType = (int)SitePageParameterType.Css,
                        ParamValue = Path,
                        SitePageId = page.Id
                    });
                }
            }
        }

        [HttpPost]
        public void AdvancedMeta(FormCollection elements)
        {
            int SitePageId = Convert.ToInt32(elements["SitePageId"]);
            string MetaName = elements["MetaName"];
            string MetaValue = elements["MetaValue"];

            SitePage page = PersistData.AvailablePages.First(p => p.Id == SitePageId);
            if (page != null && MetaName.Trim().Length > 0 && MetaValue.Trim().Length > 0)
            {
                if (page.SitePageParameters != null && !page.SitePageParameters.Any(p => p.ParamName == MetaName && p.ParamValue == MetaValue && p.ParamType == (int)SitePageParameterType.CustomMetaTag ))
                {
                    PersistDataUpdater.AddParameterToPage(page, new SitePageParameter
                    {
                        ParamName = MetaName,
                        ParamType = (int)SitePageParameterType.CustomMetaTag,
                        ParamValue = MetaValue,
                        SitePageId = page.Id
                    });
                }
            }
        }


        public void AdvancedItemDelete(int? id)
        {
            if (id.HasValue)
            {
                PersistDataUpdater.RemoveParameterFromPage(id.Value);
            }
        }


        #endregion

        #region Actions Tab

        public ActionResult Actions(int? id)
        {
            return View();
        }

        #endregion

        #endregion

        #region [ Page Detail Button Actions ]

        [HttpPost]
        public string GenerateDraftPage(int? id)
        {
            // generate draft page for current page
            // redirect to draft edit
            if (id.HasValue)
            {
                SitePage draft = PersistDataUpdater.GetDraftPage(id.Value);
                return draft.Name;
            }
            return string.Empty;
        }

        [HttpPost]
        public string PublishDraftPage(int? id)
        {
            if (id.HasValue)
            {
                SitePage page = PersistDataUpdater.PublishDraftPage(id.Value);
                return page.Id.ToString();
            }
            return string.Empty;
        }

        [HttpPost]
        public string CancelDraftPage(int? id)
        {
            if (id.HasValue)
            {
                PersistDataUpdater.CleanDrafts(id.Value);
                return PersistData.AvailablePages.Find(p => p.Id == id.Value).LocalName;
            }
            return string.Empty;
        }

        #endregion

        #region [ Menu Actions ] : [Add][ChangeStatus][CopyAs]

        public ActionResult Add(int? id)
        {
            ViewData["Layouts"] = PersistData.AllLayouts.ToList();
            if (id.HasValue)
            {
                SitePage parentPage = PersistData.AvailablePages.First(p => p.Id == id.Value);

                SitePage newSitePage = new SitePage();
                newSitePage.ParentId = parentPage.Id;
                newSitePage.CountrySiteId = parentPage.CountrySiteId;
                newSitePage.PageLayoutId = parentPage.PageLayoutId;
                newSitePage.Name = "New Page";
                newSitePage.ImagePath = defaultImagePath.Replace("~", string.Empty);
                newSitePage.ShowInRightMenu = true;
                return View(newSitePage);
            }
            else
            {
                SitePage newPage = new SitePage();
                newPage.CountrySiteId = PersistData.CurrentSite.Id;
                newPage.ImagePath = defaultImagePath.Replace("~", string.Empty);
                newPage.MenuImagePath = string.Empty;
                newPage.ShowInRightMenu = true;
                return View(newPage);
            }
        }

        public ActionResult ChangeStatus(int? id)
        {
            if (id.HasValue)
            {
                SitePage page = PersistData.AvailablePages.Find(p => p.Id == id.Value);
                if (page != null)
                {
                    // reverse
                    page.IsPublished = !page.IsPublished;
                    // disable all sub pages
                    if (!page.IsPublished)
                    {
                        List<SitePage> subPages = GKFX.Common.UI.MVC.HtmlHelperExtensions.GetSubPages(page);
                        foreach (SitePage subP in subPages)
                        {
                            subP.IsPublished = false;
                            PersistData.AvailablePages.Update(p => p.Id == subP.Id, subP);
                        }
                    }
                    PersistData.AvailablePages.Update(p => p.Id == id.Value, page);
                }
                return View(page);
            }
            return View();
        }

        public ActionResult CopyAs(int? id)
        {
            ViewData["Layouts"] = PersistData.AllLayouts.ToList();
            if (id.HasValue)
            {
                SitePage parentPage = PersistData.AvailablePages.First(p => p.Id == id.Value);
                parentPage.Id = 0;
                return View(parentPage);
            }
            else
            {
                return View(new SitePage());
            }
        }

        /// <summary>
        /// Authorized Post-Save Method for page
        /// </summary>
        /// <param name="sitePage"></param>
        [HttpPost]
        public int SaveNewForm(SitePage sitePage)
        {
            sitePage.Name = sitePage.Name.ToLower();
            sitePage.LocalName = sitePage.LocalName.ToLower();
            PersistData.AvailablePages.Add(sitePage, true);
            return sitePage.Id;
        }

        #endregion

        #region [ Remote Checkers ]

        public JsonResult CheckName(string name, int? id)
        {
            if (!PersistData.AvailablePages.Any(n => n.CountrySiteId == PersistData.CurrentSite.Id && (n.Name.ToLower() == name.ToLower() || n.LocalName.ToLower() == name.ToLower()) && (id.HasValue == false || n.Id != id.Value)))
            {
                return Json(true, JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json("The name has been taken.", JsonRequestBehavior.AllowGet);
            }
        }

        public JsonResult CheckLocalName(string localName, int? id)
        {
            if (!PersistData.AvailablePages.Any(n => n.CountrySiteId == PersistData.CurrentSite.Id && (n.LocalName.ToLower() == localName.ToLower() || n.Name.ToLower() == localName.ToLower()) && (id.HasValue == false || n.Id != id.Value)))
            {
                return Json(true, JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json("The name has been taken.", JsonRequestBehavior.AllowGet);
            }
        }

        #endregion
    }
}